from django import forms
import re
from django_redis import get_redis_connection
from .models import User
from django.db.models import Q
from django.contrib.auth import login


class RegisterForm(forms.Form):
    """
    1. 判断用户名是否为空，是否已注册
    2. 判断密码是否为空，格式是否正确
    3. 判断两次密码是否一致
    4. 判断手机号码是否为空，格式是否正确
    5. 判断短信验证码是否为空，格式是否正确，是否与真实短信验证码相同
    """
    username=forms.CharField(label='用户名',max_length=20,min_length=5,
                             error_messages={
                                 'max_length':'用户名大于20',
                                 'min_length':'用户名小于5',
                                 'required':'用户名不能为空',
                             })
    password = forms.CharField(label='密码', max_length=20, min_length=5,
                               error_messages={
                                   'max_length': '密码大于20',
                                   'min_length': '密码小于6',
                                   'required': '密码不能为空',
                               })
    password_repeat = forms.CharField(label='确定密码', max_length=20, min_length=5,
                               error_messages={
                                   'max_length': '密码大于20',
                                   'min_length': '密码小于6',
                                   'required': '密码不能为空',
                               })
    telephone = forms.CharField(label='手机号', max_length=11, min_length=11,
                               error_messages={
                                   'max_length': '手机号等于11',
                                   'min_length': '手机号等于11',
                                   'required': '手机号不能为空',
                               })
    sms_captcha = forms.CharField(label='短信验证码', max_length=4, min_length=4,
                               error_messages={
                                   'max_length': '短信验证码等于4',
                                   'min_length': '短信验证码等于4',
                                   'required': '短信验证码不能为空',
                               })
    """
        1. 判断用户名是否为空，是否已注册
        2. 判断密码是否为空，格式是否正确
        3. 判断两次密码是否一致
        4. 判断手机号码是否为空，格式是否正确
        5. 判断短信验证码是否为空，格式是否正确，是否与真实短信验证码相同
    """
    #局部钩子
    def clean_username(self):
        username=self.cleaned_data.get('username')
        if  username=='':
            raise forms.ValidationError("用户名不能为空")
        elif User.objects.filter(username=username):
            raise forms.ValidationError("用户名已经注册")
        return username
    #全局钩子
    def clean(self):
        clean_data=super().clean()
        mobile = self.cleaned_data.get("telephone")
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise forms.ValidationError("手机号格式不正确")
        elif User.objects.filter(mobile=mobile).exists():
            raise forms.ValidationError("手机号已经注册")

        password = clean_data.get('password')
        password_repeat = clean_data.get('password_repeat')
        if password !=password_repeat:
            raise forms.ValidationError("密码不一致")

        redis_conn=get_redis_connection('default')
        sms_captcha = clean_data.get('sms_captcha')
        sms_code =redis_conn.get('sms_text_{}'.format(mobile)).decode('utf-8')
        if  sms_captcha != sms_code:
            raise forms.ValidationError("短信验证码错误")



class LoginForm(forms.Form):
    def __init__(self,*args,**kwargs):
        self.request=kwargs.pop("request")
        super().__init__(*args,**kwargs)
    account=forms.CharField(error_messages={"required":"账号不能为空"})
    password=forms.CharField(max_length=20,min_length=5,
                             error_messages={
                                 "max_length":"密码长度错误",
                                 "min_length":"密码长度错误",
                                 "required":"密码不能为空",
                             })

    def clean_account(self):
        account=self.cleaned_data.get("account")
        if account:
            if re.match(r"1^[3-9]\d{9}$]",account) and (len(account)<5 or len(account)>20):
                raise forms.ValidationError("账号格式不正确")
            return account
    def clean(self):
        clean_data=super().clean()
        account=clean_data.get("account")
        password=clean_data.get("password")
        remember=clean_data.get("remember")
        user_querset=User.objects.filter(Q(username=account)| Q(mobile=account))
        if user_querset:
            user=user_querset.first()
            if user.check_password(password):
                if remember:
                    self.request.session.set_expiry(14*24*60*60)
                else:
                    self.request.session.set_expiry(0)
                login(self.request,user)
            else:
                raise forms.ValidationError("账号或密码不正确")
        else:
            raise forms.ValidationError("账号或密码不正确")